package org.csu.small.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.csu.small.common.Constant;
import org.csu.small.common.ResponseCode;
import org.csu.small.common.UniformResponse;
import org.csu.small.entity.Category;
import org.csu.small.entity.Product;
import org.csu.small.persistence.CategoryMapper;
import org.csu.small.persistence.ProductMapper;
import org.csu.small.service.ICategoryService;
import org.csu.small.service.IProductService;
import org.csu.small.utils.PropertiesUtil;
import org.csu.small.utils.QiniuCloudUtil;
import org.csu.small.vo.ProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("productService")
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ICategoryService categoryService;

    @Override
    public UniformResponse<ProductVO> detail(Integer productId, int roleType) {
        if(productId == null){
            return UniformResponse.createForErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDescription());
        }
        Product product = productMapper.selectById(productId);
        if (product == null){
            return UniformResponse.createForErrorMessage("该商品不存在或删除");
        }
        if (product.getStatus() != Constant.ProductStatus.ON_SALE.getCode() && roleType == Constant.Role.CUSTOMER){
            return UniformResponse.createForErrorMessage("商品不在售，下架或其他情况");
        }

        ProductVO productVO = entityToVO(product);
        return UniformResponse.createForSuccess(productVO);
    }

    // todo 加接口使用权限
    // todo 参数类型错误
    @Override
    public UniformResponse<String> addProduct(Product product) {
        int rows = productMapper.selectCount(Wrappers.<Product>query().eq("name", product.getName()));
        if (rows > 0) {
            return UniformResponse.createForErrorMessage("商品名已存在");
        }
        rows = productMapper.insert(product);
        if (rows == 0){
            return UniformResponse.createForErrorMessage("添加商品失败");
        }
        return UniformResponse.createForSuccessMessage("添加商品成功");
    }

    @Override
    public UniformResponse<String> edit_product_info(Product product) {
        product.setUpdateTime(LocalDateTime.now());
        System.out.println(product.getDetail());
        int rows = productMapper.updateById(product);
        if (rows == 0){
            return UniformResponse.createForErrorMessage("修改商品信息失败");
        }
        return UniformResponse.createForSuccessMessage("修改商品信息成功");
    }

    @Override
    public UniformResponse<Object> getProductList(Integer categoryId, String keyword, int pageNum, int pageSize, String orderBy, int roleType) {
        // todo productListVO
        // todo 错误判断

        Page<Product> result = new Page<>();
        result.setCurrent(pageNum);
        result.setSize(pageSize);

        QueryWrapper <Product> query = new QueryWrapper<>();
        if (categoryId != null){
            List<Category> categoryList = categoryService.getDeepCategory(categoryId).getData();
            List<Integer> categoryIdList = new ArrayList<>();
            for(Category categoryItem : categoryList){
                categoryIdList.add(categoryItem.getId());
            }

            query.in("category_id", categoryIdList);
        }

        if (StringUtils.isNotBlank(keyword)){
            keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
            query.like("name", keyword);
        }

        if (roleType == Constant.Role.CUSTOMER){
            query.eq("status", Constant.ProductStatus.ON_SALE.getCode());
        }

        //sort
        if (StringUtils.isNotBlank(orderBy)){
            if (Constant.ProductListOrderBy.PRICE_ASE_DESC.contains(orderBy)){
                String [] orderByStrings = orderBy.split("_");
                if (StringUtils.equals(orderByStrings[1], "asc")){
                    query.orderByAsc(orderByStrings[0]);
                } else if (StringUtils.equals(orderByStrings[1], "desc")){
                    query.orderByDesc(orderByStrings[0]);
                }
            }
        }


        result = productMapper.selectPage(result, query);
        return UniformResponse.createForSuccess(result);
    }

    @Override
    public UniformResponse<Object> getIndexProductList() {
        List<Category> indexCategory = categoryService.getCategory(0).getData();
        List indexProducts = new ArrayList();
        int order = 0;
        for(Category category : indexCategory){
            QueryWrapper <Product> wrapper = new QueryWrapper<>();
            wrapper.eq("category_id", category.getId());
            wrapper.eq("status", Constant.ProductStatus.ON_SALE.getCode());
            List<Product> products = productMapper.selectList(wrapper);
            if (products.size() >= 5){
                products = products.subList(0, 5);
                Map productList = new HashMap();
                order ++;
                productList.put("order", order);
                productList.put("categoryId", category.getId());
                productList.put("categoryName", category.getName());
                productList.put("products", products);
                indexProducts.add(productList);
            }

        }
        return UniformResponse.createForSuccess(indexProducts);
    }

    @Override
    public UniformResponse<String> set_sale_status(Integer productId, Integer status) {
        Product product = productMapper.selectById(productId);
        product.setStatus(status);
        int rows = productMapper.updateById(product);
        if (rows == 0){
            return UniformResponse.createForErrorMessage("修改状态信息失败");
        }
        return UniformResponse.createForSuccessMessage("修改状态信息成功");
    }

    @Override
    public UniformResponse<Object> search(Integer id, String keyword, int pageNum, int pageSize) {
        // todo productListVO
        // todo 错误判断

        Page<Product> result = new Page<>();
        result.setCurrent(pageNum);
        result.setSize(pageSize);

        QueryWrapper<Product> query = new QueryWrapper<>();
        if (id != null){
            query.eq("id", id);
        }

        if (StringUtils.isNotBlank(keyword)){
            keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
            query.like("name", keyword);
        }

        result = productMapper.selectPage(result, query);
        return UniformResponse.createForSuccess(result);
    }

    @Override
    public UniformResponse product_upload(MultipartFile upload_file, String path) {
        Map<String, String> resultMap = Maps.newHashMap();
        String file_name = upload_file.getOriginalFilename();
        File folder = new File(path);
        if (!folder.exists()) {
            folder.setWritable(true);
            folder.mkdirs();
        }
        String imgPath = path + file_name;
        try {
            upload_file.transferTo(new File(imgPath));
        }catch (Exception e){
            e.printStackTrace();
        }
        if(QiniuCloudUtil.upload(path + file_name, file_name,true)){
            String uri = null;
            try {
                uri = QiniuCloudUtil.fileUrl(file_name);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            resultMap.put("uri", uri);
            return UniformResponse.createForSuccess(resultMap);
        }
        return UniformResponse.createForSuccessMessage("上传失败");
    }

    @Override
    public UniformResponse richtext_img_upload(MultipartFile upload_file, String path) {
        Map<String, String> resultMap = Maps.newHashMap();
        String file_name = upload_file.getOriginalFilename();
        File folder = new File(path);
        if (!folder.exists()) {
            folder.setWritable(true);
            folder.mkdirs();
        }
        String imgPath = path + file_name;
        try {
            upload_file.transferTo(new File(imgPath));
        }catch (Exception e){
            e.printStackTrace();
        }
        if(QiniuCloudUtil.upload(path + file_name, file_name,true)){
            String uri = null;
            try {
                uri = QiniuCloudUtil.fileUrl(file_name);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            resultMap.put("uri", uri);
            return UniformResponse.createForSuccess(resultMap);
        }
        return UniformResponse.createForSuccessMessage("上传失败");
    }

    private ProductVO entityToVO(Product product){
        ProductVO productVO = new ProductVO();
        productVO.setId(product.getId());
        productVO.setCategoryId(product.getCategoryId());
        productVO.setName(product.getName());
        productVO.setSubtitle(product.getSubtitle());
        productVO.setMainImage(product.getMainImage());
        productVO.setSubImages(product.getSubImages());
        productVO.setDetail(product.getDetail());
        productVO.setPrice(product.getPrice());
        productVO.setStock(product.getStock());
        productVO.setStatus(product.getStatus());

        productVO.setCreateTime(product.getCreateTime().toString());
        productVO.setUpdateTime(product.getUpdateTime().toString());

        Category category = categoryService.getCategoryInfo(product.getCategoryId()).getData();
        productVO.setParentCategoryId(category.getParentId());

        productVO.setImageHost(PropertiesUtil.getProperty("image.server.url"));

        return productVO;
    }

}
